package com.xiezc.fetch.spider.biquge;

import com.xiezc.common.entity.BookInfo;
import com.xiezc.common.entity.ChapterText;
import com.xiezc.common.result.BaseResult;
import com.xiezc.common.entity.Chapter;
import com.xiezc.common.result.PojoResult;
import com.xiezc.fetch.consumer.SchedualDaoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import javax.annotation.Resource;

@Slf4j
@Component
public class BiqugePipeline implements Pipeline {

    @Resource
    SchedualDaoService schedualDaoService;

    @Override
    public void process(ResultItems resultItems, Task task) {
        BookInfo bookInfo = resultItems.get("bookInfo");
        if (bookInfo != null) {
            BaseResult baseResult = schedualDaoService.addBookInfo(bookInfo);
            log.debug(" add result:{} , bookinfo: {}  ", baseResult, bookInfo);
        }
        Chapter chapter = resultItems.get("chapter");
        ChapterText chapterText = resultItems.get("chapterText");

        if (chapter != null && chapterText != null) {
            PojoResult<Integer> result = schedualDaoService.addChapter(chapter);
            log.debug(" add result:{} , chapter: {}  ", result, chapter);
            if(!result.getSuccess()){
                return;
            }
            Integer content = result.getContent();
            chapterText.setChapterId(content);
            BaseResult baseResult = schedualDaoService.addChapterText(chapterText);

            log.debug(" add result:{} , chapterText: {}  ", baseResult, chapterText);
        }

    }
}
